#!/usr/bin/python

#DATA PROCESSOR API
#BEEF WELLINGTON inc. https://github.com/beef-wellington-inc
#main programmer : bendacoder https://github.com/bendacoder/

#modification of this file is allowed (DO AT YOUR OWN RISK!)
#inheritance of classes is allowed
#recreation of shell application is allowed
#for Linux installation run the setup.sh file
#for windows installation, copy this module to the Lib folder in the Python27 directory

#import modules
import os
import pickle
import sys

#already foobar
#processing function
def process(aFile, processN, outData=False, retReadFile=False):
    #check file if exists
    if os.path.exists(aFile):
        #try to open a file
        try:
            data = open(aFile, "r")
        except:
            print("error : CANNOT OPEN FILE INPUTED")
            sys.exit()
        #initialize lists
        uopData = []
        upData = []
        #get initial data
        for item in data:
            upData.append(item)
        #format the data
        for item in upData:
            data = item.split(" ")
        #convert data into percent
        for item in data:
            try:
                item = item.split("/")
                percent = float(item[0]) / float(item[1]) * 100
                uopData.append(percent)
            except:
                print("error : CANNOT PARSE DATA INTO PERCENTS")
                sys.exit()
        #order the lists
        try:
            pData = sorted(uopData, key=float)
        except:
            print("error : CANNOT SORT PROCESSED DATA")
            sys.exit()
        #open files for saving
        try:
            os.mkdir(processN)
            os.chdir(processN)
            theComputerData = open("computerData.fubr", "wb")
        except:
            print("error : CANNOT CREATE FILES NEEDED TO SAVE DATA")
            sys.exit()
        #TEST
        #print(pData)
        #prepare data for saving
        initList = []
        #calculate average and other stats
        average = 0
        for item in pData:
            average = average + item
        average = average / len(pData)
        minimum = min(pData)
        maximum = max(pData)
        #write stats to dictionary
        resultsDict = {"average":average, "minimum":minimum, "maximum":maximum}
        #insert stats and data into main list
        initList.append(pData)
        initList.append(resultsDict)
        #save data to files
        pickle.dump(initList, theComputerData)
        #create data to write to readable file
        try:
            readData = open("readableData.txt", "w")
            readStat = open("readableStats.txt", "w")
        except:
            print("error : CANNOT CREATE FILES TO WRITE READABLE DATA")
            sys.exit()
        finalData = ""
        for item in pData:
            finalData = finalData + str(item) + "%, "
        finalStat = "average=" + str(average) + ", minimum=" + str(minimum) + ", maximum=" + str(maximum)
        readData.write(finalData)
        readStat.write(finalStat)
        #output data if needed
        if outData:
            return(initList)
    else:
        print("error : CANNOT FIND PATH")
        sys.exit()

#will totaly become foobar
#atleast the developer can understand it!
#file data unpacker
class Archive:
    #unpack while returning data
    @staticmethod
    def unPack(aFile, ldType=0):
        #check if path exists
        if os.path.exists(aFile):
            #check if file is a .fubr file
            fileExtension = aFile.split(".")
            if fileExtension[len(fileExtension) - 1] == "fubr":
                #see what parameter the function got
                if ldType == 0:
                    #load data from file
                    try:
                        return(pickle.load(open(aFile, "rb"))[0])
                    except:
                        print("error : CANNOT LOAD FILE")
                        sys.exit()
                elif ldType == 1:
                    #load data from file
                    try:
                        return(pickle.load(open(aFile, "rb"))[1])
                    except:
                        print("error : CANNOT LOAD FILE")
                        sys.exit()
                else:
                    print("error : CANNOT IDENTIFY PARAMETER")
            else:
                print("error : INVALID FILE EXTENSION")
                sys.exit()
        else:
            print("error : CANNOT FIND PATH")
            sys.exit()
    #data extractor
    @staticmethod
    def extract(aFile, inDir="null"):
        #check if path exists
        if os.path.exists(aFile):
            #check is file is a .fubr file
            exten = aFile.split(".")
            if exten[len(exten) - 1] == "fubr":
                #load file
                try:
                    data = pickle.load(open(aFile, "rb"))
                except:
                    print("error : CANNOT LOAD FILE")
                    sys.exit()
                #try to get data from file
                try:
                    dataData = data[0]
                    dataStat = data[1]
                except:
                    print("error : CANNOT LOAD DATA FROM FILE")
                    sys.exit()
                #check if a seperate directory needs to be created
                if inDir != "null":
                    os.mkdir(inDir)
                    os.chdir(inDir)
                #open new files for saving
                try:
                    fileData = open("dataFile.fubr", "wb")
                    fileStat = open("statFile.fubr", "wb")
                except:
                    print("error : CANNOT CREATE FILES NEEDED FOR EXTRACTION")
                    sys.exit()
                #save data to files
                try:
                    pickle.dump(dataData, fileData)
                    pickle.dump(dataStat, fileStat)
                except:
                    print("error : CANNOT SAVE DATA TO FILE")
                    sys.exit()
            else:
                print("error : INVALID FILE EXTENSION")
                sys.exit()
        else:
            print("error : CANNOT FIND PATH")
            sys.exit()
    #convert the binary into text
    @staticmethod
    def textConvert(aFile, dictOrList=0):
        #check if path exists
        if os.path.exists(aFile):
            #check if the file inputed is a .fubr file
            exten = aFile.split(".")
            if exten[len(exten) - 1] == "fubr":
                #open the file
                try:
                    data = pickle.load(open(aFile, "rb"))
                except:
                    print("error : CANNOT LOAD DATA FROM FILE")
                    sys.exit()
                #open new file for saving text
                try:
                    newFile = open("readableData", "w")
                except:
                    print("error : CANNOT CREATE FILE FOR SAVING TEXT")
                    sys.exit()
                #check dictOrList parameter
                if dictOrList == 0:
                    dataToSave = data[0]
                    finalData = ""
                    for item in dataToSave:
                        aString = str(item) + "%, "
                        finalData = finalData + aString
                elif dictOrList == 1:
                    dataToSave = data[1]
                    finalData = ""
                    average = str(dataToSave["average"])
                    minimum = str(dataToSave["minimum"])
                    maximum = str(dataToSave["maximum"])
                    finalData = "average=" + average + ", minimum=" + minimum + ", maximum=" + maximum
                else:
                    print("error : INVALID PARAMETER")
                    sys.exit()
                #write to file
                try:
                    newFile.write(finalData)
                except:
                    print("error : CANNOT WRITE DATA")
                    sys.exit()
            else:
                print("error : INVALID FILE EXTENSION")
                sys.exit()
        else:
            print("error :  CANNOT FIND PATH")
            sys.exit()
    #converts data to text into two files
    @staticmethod
    def dTextConvert(aFile, nExten="txt"):
    	#check if the path of the file exists
        if os.path.exists(aFile):
            #check extension
            exten = aFile.split(".")
            if exten[len(exten) - 1] == "fubr":
                try:
                    newStatFile = open("readStats." + nExten, "w")
                    newDataFile = open("readData." + nExten, "w")
                except:
                    print("error : CANNOT CREATE FILES NEEDED FOR SAVING")
                    sys.exit()
                try:
                    data = pickle.load(open(aFile, "rb"))
                except:
                    print("error : CANNOT LOAD DATA")
                    sys.exit()
                try:
                    dictData = data[1]
                    average = str(dictData["average"])
                    minimum = str(dictData["minimum"])
                    maximum = str(dictData["maximum"])
                    finalStatData = "average=" + average + ", minimum=" + minimum + ", maximum=" + maximum
                except:
                    print("error : CANNOT CREATE DATA FOR WRITING")
                    sys.exit()
                try:
                    try:
                        data = pickle.load(open(aFile, "rb"))
                        dataData = data[0]
                    except:
                        print("error : CANNOT LOAD DATA")
                        sys.exit()
                    finalDataData = ""
                    try:
                        for percent in dataData:
                            percent = str(percent) + "%, "
                            finalDataData = finalDataData + percent
                    except:
                        print("error : CANNOT CREATE DATA FOR SAVING")
                        sys.exit()
                except:
                    print("error : CANNOT CREATE DATA FOR WRITING")
                    sys.exit()
                try:
                    newStatFile.write(finalStatData)
                    newDataFile.write(finalDataData)
                except:
                    print("error : CANNOT WRITE DATA TO FILE")
                    sys.exit()
            else:
                print("error : INVALID FILE EXTENSION")
                sys.exit()
        else:
            print("error : CANNOT FIND PATH")
            sys.exit()
    #prints out data
    @staticmethod
    def prints(aFile):
        if os.path.exists(aFile):
            exten = aFile.split(".")
            if exten[len(exten) - 1] == "fubr":
                data = pickle.load(open(aFile, "rb"))
                average = str(data[1]["average"])
                minimum = str(data[1]["minimum"])
                maximum = str(data[1]["maximum"])
                stats = "average=" + average + ",\nminimum=" + minimum + ",\nmaximum=" + maximum
                db = ""
                for item in data[0]:
                    db = db + str(item) + "%,\n"
                print(stats)
                print("\n")
                print(db)
            else:
                print("error : INVALID FILE EXTENSION")
                sys.exit()
        else:
            print("error : CANNOT FIND PATH")
            sys.exit()
    @staticmethod
    def save(aFile, newFile):
        #see if file exists
        if os.path.exists(aFile):
            exten = aFile.split(".")
	    if exten[len(exten) - 1] == "fubr":
                try:
                    data = pickle.load(open(aFile, "rb"))
                except:
                    print("error : CANNOT LOAD FILE")
                    sys.exit()
                if not isinstance(data, list):
                    print("error : DATA FROM FILE NOT IN PROPER FORMAT")
                    sys.exit()
                try:
                    dataData = data[0]
                    dataStat = data[1]
                except:
                    print("error : CANNOT GET DATA FROM OPENED FILE")
                    sys.exit()
                try:
                    finalDataData = ""
                    for percent in dataData:
                        percent = str(percent) + "%, "
                        finalDataData = finalDataData + percent
                except:
                    print("error : CANNOT GET PERCENTS FROM DATABASE")
                    sys.exit()
                try:
                    average = "average=" + str(dataStat["average"]) + ", "
                    minimum = "minimum=" + str(dataStat["minimum"]) + ", "
                    maximum = "maximum=" + str(dataStat["maximum"]) + ", "
                    finalDataStat = average + minimum + maximum
                except:
                    print("error : CANNOT GET DATA FROM OPENED FILE")
                    sys.exit()
                try:
                    nexten = newFile.split(".")
                    if nexten[len(nexten) - 1] == "fdp":
                        try:
                            data.append(finalDataData)
                            data.append(finalDataStat)
                        except:
                            print("error : CANNOT ADD EXTR DATA TO MAIN DATABASE")
                            sys.exit()
                    else:
                        print("error : NOT A fdp FILE")
                        sys.exit()
                except:
                    pass
                try:
                    pickle.dump(data, open(newFile, "wb"))
                except:
                    print("error : CANNOT SAVE DATA TO NEW FILE")
                    sys.exit()
            else:
                print("error : INVALID FILE EXTENSION")
                sys.exit()
        else:
            print("error : CANNOR FIND PATH")
            sys.exit()

#non static class for data Processor API
class Processor:
    def __init__(self, aFileR):
        if not os.path.exists(aFileR):
            print("error : CANNOT FIND FILE INPUTED")
            sys.exit()
        self.FileR = aFileR
        self.data = []
        self.dataData = []
        self.dataStat = {}
    #process the data
    def process(self, name="Process", out=False, get=True):
        try:
            process(self.FileR, name, out)
        except:
            print("error : CANNOR EXECUTE PROCESS FUNCTION")
            sys.exit()
        if get == True:
            try:
                Rdata = pickle.load(open("computerData.fubr", "rb"))
            except:
                print("error : CANNOT OPEN FILE FOR READING DATA")
                sys.exit()
            self.dataData = Rdata[0]
            self.dataStat = Rdata[1]
            self.data.append(self.dataData)
            self.data.append(self.dataStat)
    #create save file
    def save(self, extension="fubr", doubleE=False):
        try:
            temp = open("data." + extension, "w")
            temp.close()
        except:
            print("error : CANNOT CREATE FILE FOR SAVING")
            sys.exit()
        try:
            aFile = open("data." + extension, "wb")
        except:
            print("error : CANNOT OPEN FILE FOR SAVING")
            sys.exit()
        try:
            pickle.dump(self.data, aFile)
        except:
            print("error : CANNOT SAVE TO FILE")
            sys.exit()
        if doubleE == True:
            try:
                dataStats = open("dataStats." + extension, "wb")
                dataDataB = open("dataDataB." + extension, "wb")
            except:
                print("error : CANNOT CREATE FILES FOR SAVING")
                sys.exit()
            try:
                pickle.dump(self.dataData, dataDataB)
                pickle.dump(self.dataStat, dataStats)
            except:
                print("error : CANNOT SAVE DATA TO FILE")
                sys.exit()
